﻿using System;
using System.Collections.Generic;
using System.Linq;
using Apps.Models;
using Apps.Common;
using Microsoft.Practices.Unity;
using System.Transactions;
using Apps.BLL.Core;
using Apps.Locale;
using LinqToExcel;
using System.IO;
using System.Text;
using System.Linq.Expressions;
using Apps.IDAL.S;
using Apps.Models.S;
using Apps.IBLL.S;

namespace Apps.BLL.S
{
    public partial class S_SAMPLE_SAVEBLL: Virtual_S_SAMPLE_SAVEBLL, IS_SAMPLE_SAVEBLL
    {
        public List<V_S_SAMPLE_SAVE> GetList(ref GridPager pager, string queryStr, string sDate, string eDate)
        {
            using (DBContainer db = new DBContainer())
            {
                var whereLambda = PredicateBuilder.True<V_S_SAMPLE_SAVE>();
                DateTime sdate = string.IsNullOrEmpty(sDate) ? DateTime.MinValue : DateTime.Parse(sDate).Date;
                DateTime edate = string.IsNullOrEmpty(eDate) ? DateTime.Now.AddDays(1).Date : DateTime.Parse(eDate).AddDays(1).Date;
                if (!string.IsNullOrWhiteSpace(queryStr))
                {
                    whereLambda = whereLambda.And(a => (
                                        (a.BATCH_CODE.Contains(queryStr)
                                       || a.TRUENAME.Contains(queryStr))
                                       && ((a.SAMPLE_CODE.Contains(queryStr)) || (a.TEST_CODE.Contains(queryStr))) && (a.SAVE_TIME >= sdate && a.SAVE_TIME <= edate)
                    ));
                }

                IQueryable<V_S_SAMPLE_SAVE> queryData = db.V_S_SAMPLE_SAVE.Where(whereLambda.Compile()).AsQueryable();
                pager.totalRows = queryData.Count();
                //排序
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                return queryData.ToList();
            }
        }

        public List<V_S_SAMPLE_SAVE> GetList(ref GridPager pager, string queryStr, string queryStr2, string sDate, string eDate)
        {
            try
            {

                using (DBContainer db = new DBContainer())
                {
                    IQueryable<V_S_SAMPLE_SAVE> queryData = db.V_S_SAMPLE_SAVE.AsQueryable();
                    var whereLambda = PredicateBuilder.True<V_S_SAMPLE_SAVE>();
                    DateTime sdate = string.IsNullOrEmpty(sDate) ? DateTime.MinValue : DateTime.Parse(sDate).Date;
                    DateTime edate = string.IsNullOrEmpty(eDate) ? DateTime.Now.AddDays(1).Date : DateTime.Parse(eDate).AddDays(1).Date;
                    whereLambda = whereLambda.And<V_S_SAMPLE_SAVE>(a => (a.SAVE_TIME >= sdate && a.SAVE_TIME <= edate));
                    if (!string.IsNullOrEmpty(queryStr))
                    {
                        whereLambda = whereLambda.And<V_S_SAMPLE_SAVE>(a => (
                                            (a.BATCH_CODE.Contains(queryStr)
                                            || a.TRUENAME.Contains(queryStr)))
                        );
                    }
                    if (!string.IsNullOrEmpty(queryStr2))
                    {
                        whereLambda = whereLambda.And<V_S_SAMPLE_SAVE>(a => (
                                            (a.SAMPLE_CODE.Contains(queryStr2) || (a.TEST_CODE!=null&&a.TEST_CODE.Contains(queryStr2))))
                        );
                    }
                    queryData = queryData.Where(whereLambda.Compile()).AsQueryable();
                    pager.totalRows = queryData.Count();
                    //排序
                    queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                    return queryData.ToList();
                }
            }
            catch (Exception )
            {

                throw;
            }
        }
        
    }
    public class Virtual_S_SAMPLE_SAVEBLL
    {
        [Dependency]
        public IS_SAMPLE_SAVERepository m_Rep { get; set; }

        public virtual List<S_SAMPLE_SAVEModel> GetList(ref GridPager pager, string queryStr)
        {

            IQueryable<S_SAMPLE_SAVE> queryData = null;
            if (!string.IsNullOrWhiteSpace(queryStr))
            {
                queryData = m_Rep.GetList(
                                a => a.SAVE_ID.Contains(queryStr)
                                || a.SAMPLE_ID.Contains(queryStr)
                                || a.LOCKER_ID.Contains(queryStr)
                                || a.SAVE_USER_ID.Contains(queryStr)

                                );
            }
            else
            {
                queryData = m_Rep.GetList();
            }
            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<S_SAMPLE_SAVEModel> GetPagerList(ref GridPager pager, Expression<Func<S_SAMPLE_SAVE, bool>> whereLambda)
        {

            IQueryable<S_SAMPLE_SAVE> queryData = m_Rep.GetList(whereLambda);

            pager.totalRows = queryData.Count();
            //排序
            queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
            return CreateModelList(ref queryData);
        }

        public virtual List<S_SAMPLE_SAVEModel> GetList(Expression<Func<S_SAMPLE_SAVE, bool>> whereLambda)
        {

            IQueryable<S_SAMPLE_SAVE> queryData = m_Rep.GetList(whereLambda);

            return CreateModelList(ref queryData);
        }

        public virtual List<S_SAMPLE_SAVEModel> GetListByParentId(ref GridPager pager, string queryStr, object parentId)
        {
            return new List<S_SAMPLE_SAVEModel>();
        }

        public virtual List<S_SAMPLE_SAVEModel> CreateModelList(ref IQueryable<S_SAMPLE_SAVE> queryData)
        {

            List<S_SAMPLE_SAVEModel> modelList = (from r in queryData
                                                  select new S_SAMPLE_SAVEModel
                                                  {
                                                      SAVE_ID = r.SAVE_ID,
                                                      SAMPLE_ID = r.SAMPLE_ID,
                                                      LOCKER_ID = r.LOCKER_ID,
                                                      SAVE_USER_ID = r.SAVE_USER_ID,
                                                      SAVE_TIME = r.SAVE_TIME,

                                                  }).ToList();

            return modelList;
        }

        public virtual List<V_S_SAMPLE_SAVE> CreateModelList(ref IQueryable<V_S_SAMPLE_SAVE> queryData)
        {

            List<V_S_SAMPLE_SAVE> modelList = queryData.ToList();

            return modelList;
        }

        public virtual bool Create(ref ValidationErrors errors, S_SAMPLE_SAVEModel model)
        {
            try
            {
                S_SAMPLE_SAVE entity = m_Rep.GetById(model.SAVE_ID);
                if (entity != null)
                {
                    errors.Add(Resource.PrimaryRepeat);
                    return false;
                }
                entity = new S_SAMPLE_SAVE();
                entity.SAVE_ID = model.SAVE_ID;
                entity.SAMPLE_ID = model.SAMPLE_ID;
                entity.LOCKER_ID = model.LOCKER_ID;
                entity.SAVE_USER_ID = model.SAVE_USER_ID;
                entity.SAVE_TIME = model.SAVE_TIME;


                if (m_Rep.Create(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.InsertFail);
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }


        public virtual bool Deletes(ref ValidationErrors errors, Expression<Func<S_SAMPLE_SAVE, bool>> whereLambda)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {

                    foreach (var entity in db.S_SAMPLE_SAVE.Where(whereLambda))
                    {
                        db.Entry(entity).State = System.Data.Entity.EntityState.Deleted;
                    }

                    if (db.SaveChanges() > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
                    }

                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object id)
        {
            try
            {
                if (m_Rep.Delete(id) == 1)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public virtual bool Delete(ref ValidationErrors errors, object[] deleteCollection)
        {
            try
            {
                if (deleteCollection != null)
                {
                    using (TransactionScope transactionScope = new TransactionScope())
                    {
                        if (m_Rep.Delete(deleteCollection) == deleteCollection.Length)
                        {
                            transactionScope.Complete();
                            return true;
                        }
                        else
                        {
                            Transaction.Current.Rollback();
                            return false;
                        }
                    }
                }
                return false;
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }




        public virtual bool Edit(ref ValidationErrors errors, S_SAMPLE_SAVEModel model)
        {
            try
            {
                S_SAMPLE_SAVE entity = m_Rep.GetById(model.SAVE_ID);
                if (entity == null)
                {
                    errors.Add(Resource.Disable);
                    return false;
                }
                entity.SAVE_ID = model.SAVE_ID;
                entity.SAMPLE_ID = model.SAMPLE_ID;
                entity.LOCKER_ID = model.LOCKER_ID;
                entity.SAVE_USER_ID = model.SAVE_USER_ID;
                entity.SAVE_TIME = model.SAVE_TIME;



                if (m_Rep.Edit(entity))
                {
                    return true;
                }
                else
                {
                    errors.Add(Resource.NoDataChange);
                    return false;
                }

            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }



        public virtual S_SAMPLE_SAVEModel GetById(object id)
        {
            if (IsExists(id))
            {
                S_SAMPLE_SAVE entity = m_Rep.GetById(id);
                S_SAMPLE_SAVEModel model = new S_SAMPLE_SAVEModel();
                model.SAVE_ID = entity.SAVE_ID;
                model.SAMPLE_ID = entity.SAMPLE_ID;
                model.LOCKER_ID = entity.LOCKER_ID;
                model.SAVE_USER_ID = entity.SAVE_USER_ID;
                model.SAVE_TIME = entity.SAVE_TIME;

                return model;
            }
            else
            {
                return null;
            }
        }

        public virtual S_SAMPLE_SAVEModel GetItem(Expression<Func<S_SAMPLE_SAVE, bool>> whereLambda)
        {

            S_SAMPLE_SAVE entity = m_Rep.GetItem(whereLambda);
            if (entity == null) return null;

            S_SAMPLE_SAVEModel model = new S_SAMPLE_SAVEModel();
            model.SAVE_ID = entity.SAVE_ID;
            model.SAMPLE_ID = entity.SAMPLE_ID;
            model.LOCKER_ID = entity.LOCKER_ID;
            model.SAVE_USER_ID = entity.SAVE_USER_ID;
            model.SAVE_TIME = entity.SAVE_TIME;

            return model;
        }


        /// <summary>
        /// 校验Excel数据,这个方法一般用于重写校验逻辑
        /// </summary>
        public virtual bool CheckImportData(string fileName, List<S_SAMPLE_SAVEModel> list, ref ValidationErrors errors)
        {

            var targetFile = new FileInfo(fileName);

            if (!targetFile.Exists)
            {

                errors.Add("导入的数据文件不存在");
                return false;
            }

            var excelFile = new ExcelQueryFactory(fileName);

            //对应列头
            excelFile.AddMapping<S_SAMPLE_SAVEModel>(x => x.SAVE_ID, "SAVE_ID");
            excelFile.AddMapping<S_SAMPLE_SAVEModel>(x => x.SAMPLE_ID, "SAMPLE_ID");
            excelFile.AddMapping<S_SAMPLE_SAVEModel>(x => x.LOCKER_ID, "LOCKER_ID");
            excelFile.AddMapping<S_SAMPLE_SAVEModel>(x => x.SAVE_USER_ID, "SAVE_USER_ID");
            excelFile.AddMapping<S_SAMPLE_SAVEModel>(x => x.SAVE_TIME, "SAVE_TIME");

            //SheetName
            var excelContent = excelFile.Worksheet<S_SAMPLE_SAVEModel>(0);
            int rowIndex = 1;
            //检查数据正确性
            foreach (var row in excelContent)
            {
                var errorMessage = new StringBuilder();
                var entity = new S_SAMPLE_SAVEModel();
                entity.SAVE_ID = row.SAVE_ID;
                entity.SAMPLE_ID = row.SAMPLE_ID;
                entity.LOCKER_ID = row.LOCKER_ID;
                entity.SAVE_USER_ID = row.SAVE_USER_ID;
                entity.SAVE_TIME = row.SAVE_TIME;

                //=============================================================================
                if (errorMessage.Length > 0)
                {
                    errors.Add(string.Format(
                        "第 {0} 列发现错误：{1}{2}",
                        rowIndex,
                        errorMessage,
                        "<br/>"));
                }
                list.Add(entity);
                rowIndex += 1;
            }
            if (errors.Count > 0)
            {
                return false;
            }
            return true;
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        public virtual void SaveImportData(IEnumerable<S_SAMPLE_SAVEModel> list)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    foreach (var model in list)
                    {
                        S_SAMPLE_SAVE entity = new S_SAMPLE_SAVE();
                        entity.SAVE_ID = model.SAVE_ID;
                        entity.SAMPLE_ID = model.SAMPLE_ID;
                        entity.LOCKER_ID = model.LOCKER_ID;
                        entity.SAVE_USER_ID = model.SAVE_USER_ID;
                        entity.SAVE_TIME = model.SAVE_TIME;

                        db.S_SAMPLE_SAVE.Add(entity);
                    }
                    db.SaveChanges();
                }
            }
            catch
            {
                throw;
            }
        }


        public virtual bool IsExists(object id)
        {
            return m_Rep.IsExist(id);
        }
        public void Dispose()
        {

        }

    }
}
